/**
 * 
 */
package org.arpit.masteringextjs.dao.impl;

import java.util.List;

import org.arpit.masteringextjs.dao.DBUtility;
import org.arpit.masteringextjs.dao.LanguageDAO;
import org.arpit.masteringextjs.domain.Country;
import org.arpit.masteringextjs.domain.Language;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

/**
 * @author arpit
 *
 */
public class LanguageDAOImpl implements LanguageDAO{

	private static LanguageDAO actorDAO;
	private SessionFactory sessionFactory = DBUtility.getSessionFactory();
	private LanguageDAOImpl () {
		
	}
	
	public static LanguageDAO getInstance() {
		if(actorDAO == null) {
			actorDAO = new LanguageDAOImpl();
		}
		return actorDAO;
	}
	
	@Override
	public List<Language> findAll() {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(Language.class);
		crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		List<Language> actors = crit.list();
		session.getTransaction().commit();
		session.close();
		return actors;
	}

	@Override
	public Language create(Language actor) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Language createdActor = (Language) session.merge(actor);
		session.getTransaction().commit();
		session.close();
		return createdActor;
	}

	@Override
	public Language update(Language language) {
		if(language.getId() == null || language.getId() == 0) {
			throw new IllegalArgumentException("Invalid data");
		}
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Language updatedLanguage = (Language) session.merge(language);
		session.getTransaction().commit();
		session.close();
		return updatedLanguage;
	}

	@Override
	public void delete(long id) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(Language.class);
		crit.add(Restrictions.eq("id", id));
		List<Language> languages = crit.list();
		if(languages.isEmpty()) {
			throw new IllegalArgumentException("Language with id " + id +" not found");
		}
		Language language = languages.get(0);
		session.delete(language);
		session.getTransaction().commit();
		session.close();
	}

}
